package com.lwt.util;

import com.lwt.constant.TongchouConstant;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 判断请求类型的工具方法
 *
 * @Author Li Weitong
 * @Date 2021/1/14 18:01
 */
public class TongchouUtil {

    /**
     * 判断当前请求是否是ajax请求，以ajax请求体信息作为依据判断
     *
     * @param request
     * @return true为当前是ajax请求
     */
    public static boolean judgeRequestType(HttpServletRequest request) {
        // 获取请求消息头
        String acceptHeader = request.getHeader("Accept");
        String xRequestHeader = request.getHeader("X-Requested-With");
        // 请求类型的判断依据
//        if (
//                (acceptHeader != null&&acceptHeader.contains("application/json")) ||
//                        (xRequestHeader != null&&xRequestHeader.equals("XMLHttpRequest"))
//        ) {
//            return true;
//        }else {
//            return false;
//        }
        return (acceptHeader != null && acceptHeader.contains("application/json")) ||
                (xRequestHeader != null && xRequestHeader.equals("XMLHttpRequest"));
    }

    /**
     * 对明文字符串进行md5加密
     * @param source 传入的明文
     * @return
     */
    public static String md5(String source) {
        if (source == null || source.length() == 0) {
            throw new RuntimeException(TongchouConstant.MESSAGE_STRING_INVALIDATE);
        }
        String algorithm = "md5";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            byte[] input = source.getBytes();
            byte[] output = messageDigest.digest(input);
            int signum = 1;
            BigInteger bigInteger = new BigInteger(signum, output);
            int radix = 16; // 16进制
            String encoded = bigInteger.toString(radix).toUpperCase();
            return encoded;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
